package com.aspire.shiro.realm;

import com.aspire.shiro.service.SecurityService;
import com.aspire.shiro.service.impl.SecurityServiceImpl;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * 自定义realm，改造获取用户信息从ini文件改为从数据库模拟获取
 */
public class DefinitionRealm extends AuthorizingRealm {

    /**
     * 重写认证方法
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取登录名
        String username = (String) token.getPrincipal();
        //模拟从数据库获取密码
        SecurityService securityService = new SecurityServiceImpl();
        String password = securityService.getPasswordByUsername(username);
        //构建AuthenticationInfo对象(使用AuthenticationInfo的实现SimpleAuthenticationInfo对象)
        SimpleAuthenticationInfo authentication = new SimpleAuthenticationInfo(username,password,getName());
        return authentication;
    }

    /**
     * 重写鉴权方法
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }


}
